import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

// 路由懒加载
const Login = () => import('@/views/Login')
const Register = () => import('@/views/Register')
const NotFound = () => import('@/views/404')
const AdminLogin = () => import('@/views/AdminLogin')

// 用户端
const UserLayout = () => import('@/views/user/Layout')
const Home = () => import('@/views/user/Home')
const Shop = () => import('@/views/user/Shop')
const Order = () => import('@/views/user/Order')
const OrderDetail = () => import('@/views/user/OrderDetail')
const Profile = () => import('@/views/user/Profile')
const UserProductDetail = () => import('@/views/user/ProductDetail')
const SearchResults = () => import('@/views/user/SearchResults')
const Checkout = () => import('@/views/user/Checkout')

// 商家端
const MerchantLayout = () => import('@/views/merchant/Layout')
const MerchantHome = () => import('@/views/merchant/Home')
// const MerchantProduct = () => import('@/views/merchant/Product')
const MerchantOrder = () => import('@/views/merchant/Order')
const MerchantProfile = () => import('@/views/merchant/Profile')
const ProductList = () => import('@/views/merchant/product/List')
const ProductEdit = () => import('@/views/merchant/product/Edit')
const ProductDetail = () => import('@/views/merchant/product/Detail')

// 骑手端
const RiderLayout = () => import('@/views/rider/Layout')
const RiderHome = () => import('@/views/rider/Home')
const RiderOrder = () => import('@/views/rider/Order')
const RiderProfile = () => import('@/views/rider/Profile')
const RiderRatings = () => import('@/views/rider/Ratings')

// 平台管理端
const AdminLayout = () => import('@/views/admin/Layout')
const AdminHome = () => import('@/views/admin/Home')
const AdminCategory = () => import('@/views/admin/Category')
const AdminReport = () => import('@/views/admin/Report')
const AdminMerchantAudit = () => import('@/views/admin/merchant/Audit')
const AdminMerchantList = () => import('@/views/admin/merchant/List')
const AdminRiderAudit = () => import('@/views/admin/rider/Audit')
const AdminRiderList = () => import('@/views/admin/rider/List')
const AdminOrderMonitor = () => import('@/views/admin/order/Monitor')
const AdminOrderStatistics = () => import('@/views/admin/order/Statistics')

const routes = [
  {
    path: '/login',
    component: Login,
    meta: { title: '登录' }
  },
  {
    path: '/admin/login',
    component: AdminLogin,
    meta: { title: '管理员登录' }
  },
  {
    path: '/register',
    component: Register,
    meta: { title: '注册' }
  },
  {
    path: '/',
    component: UserLayout,
    redirect: '/home',
    children: [
      {
        path: 'home',
        component: Home,
        meta: { title: '首页' }
      },
      {
        path: 'shop/:id',
        component: Shop,
        meta: { title: '商家详情' }
      },
      {
        path: 'order',
        component: Order,
        meta: { title: '我的订单', requireAuth: true }
      },
      {
        path: 'order/:id',
        component: OrderDetail,
        meta: { title: '订单详情', requireAuth: true }
      },
      {
        path: 'profile',
        component: Profile,
        meta: { title: '个人中心', requireAuth: true }
      },
      {
        path: 'product/:id',
        component: UserProductDetail,
        meta: { title: '商品详情' }
      },
      {
        path: 'search-results',
        component: SearchResults,
        meta: { title: '搜索结果' }
      },
      {
        path: 'checkout',
        component: Checkout,
        meta: { title: '确认订单', requireAuth: true }
      }
    ]
  },
  {
    path: '/merchant',
    component: MerchantLayout,
    redirect: '/merchant/home',
    children: [
      {
        path: 'home',
        component: MerchantHome,
        meta: { title: '商家首页', requireAuth: true, role: 'merchant' }
      },
      {
        path: 'product',
        component: ProductList,
        meta: { title: '商品管理', requireAuth: true, role: 'merchant' }
      },
      {
        path: 'product/list',
        component: ProductList,
        meta: { title: '商品列表', requireAuth: true, role: 'merchant' }
      },
      {
        path: 'product/add',
        component: ProductEdit,
        meta: { title: '添加商品', requireAuth: true, role: 'merchant' }
      },
      {
        path: 'product/edit/:id',
        component: ProductEdit,
        meta: { title: '编辑商品', requireAuth: true, role: 'merchant' }
      },
      {
        path: 'product/detail/:id',
        component: ProductDetail,
        meta: { title: '商品详情', requireAuth: true, role: 'merchant' }
      },
      {
        path: 'order',
        component: MerchantOrder,
        meta: { title: '订单管理', requireAuth: true, role: 'merchant' }
      },
      {
        path: 'profile',
        component: MerchantProfile,
        meta: { title: '商家信息', requireAuth: true, role: 'merchant' }
      }
    ]
  },
  {
    path: '/rider',
    component: RiderLayout,
    redirect: '/rider/home',
    children: [
      {
        path: 'home',
        component: RiderHome,
        meta: { title: '骑手首页', requireAuth: true, role: 'rider' }
      },
      {
        path: 'order',
        component: RiderOrder,
        meta: { title: '订单管理', requireAuth: true, role: 'rider' }
      },
      {
        path: 'profile',
        component: RiderProfile,
        meta: { title: '骑手信息', requireAuth: true, role: 'rider' }
      },
      {
        path: 'ratings',
        component: RiderRatings,
        meta: { title: '我的评价', requireAuth: true, role: 'rider' }
      }
    ]
  },
  {
    path: '/admin',
    component: AdminLayout,
    redirect: '/admin/home',
    children: [
      {
        path: 'home',
        component: AdminHome,
        meta: { title: '平台首页', requireAuth: true, role: 'admin' }
      },
      {
        path: 'merchant/audit',
        component: AdminMerchantAudit,
        meta: { title: '商家审核', requireAuth: true, role: 'admin' }
      },
      {
        path: 'merchant/list',
        component: AdminMerchantList,
        meta: { title: '商家列表', requireAuth: true, role: 'admin' }
      },
      {
        path: 'rider/audit',
        component: AdminRiderAudit,
        meta: { title: '骑手审核', requireAuth: true, role: 'admin' }
      },
      {
        path: 'rider/list',
        component: AdminRiderList,
        meta: { title: '骑手列表', requireAuth: true, role: 'admin' }
      },
      {
        path: 'order/monitor',
        component: AdminOrderMonitor,
        meta: { title: '订单监控', requireAuth: true, role: 'admin' }
      },
      {
        path: 'order/statistics',
        component: AdminOrderStatistics,
        meta: { title: '订单统计', requireAuth: true, role: 'admin' }
      },
      {
        path: 'dispatch/config',
        component: () => import(/* webpackChunkName: "admin-dispatch" */ '../views/admin/dispatch/Config.vue'),
        meta: { title: '调度配置', requireAuth: true, role: 'admin' }
      },
      {
        path: 'category',
        component: AdminCategory,
        meta: { title: '分类管理', requireAuth: true, role: 'admin' }
      },
      {
        path: 'report',
        component: AdminReport,
        meta: { title: '报表管理', requireAuth: true, role: 'admin' }
      }
    ]
  },
  {
    path: '/404',
    component: NotFound,
    meta: { title: '页面不存在' }
  },
  {
    path: '*',
    redirect: '/404'
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 导航守卫
router.beforeEach((to, from, next) => {
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - 美味外卖` : '美味外卖'

  // 检查是否需要登录权限
  if (to.matched.some(record => record.meta.requireAuth)) {
    const token = localStorage.getItem('token')
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')

    if (!token) {
      // 如果是访问管理员页面，重定向到管理员登录页
      if (to.path.startsWith('/admin') && to.path !== '/admin/login') {
        next({
          path: '/admin/login',
          query: { redirect: to.fullPath }
        })
      } else {
        next({
          path: '/login',
          query: { redirect: to.fullPath }
        })
      }
    } else {
      // 检查角色权限
      if (to.meta.role && to.meta.role !== userInfo.role) {
        // 如果尝试访问管理员页面但没有管理员权限，重定向到管理员登录页
        if (to.meta.role === 'admin') {
          next({
            path: '/admin/login',
            query: { redirect: to.fullPath }
          })
        } else {
          next('/404')
        }
      } else {
        next()
      }
    }
  } else {
    next()
  }
})

export default router 